package com.github.lh.common;

import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * @author <a href="mailto:393803588@qq.com">HanL(liuhan3)</a>
 * @date 17-12-13
 */
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class BindingResultChecker {

    private BindingResult result;

    public static BindingResultChecker checkNoErrors(BindingResult result) {
        return new BindingResultChecker(result);
    }

    public <T> ReturnModel<?> then(Supplier<ReturnModel<T>> bizMethod) {
        if (result.hasErrors()) {
            return ReturnModel.just(ReturnCode.BAD_REQUEST, extractErrorsReturn(this.result));
        } else {
            return bizMethod.get();
        }
    }

    public static String extractErrorsReturn(BindingResult result) {
        return result.getAllErrors().stream()
                .map(ObjectError::getDefaultMessage)
                .collect(Collectors.joining(","));
    }
}
